package com.zt.bus.line.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.zt.bus.constant.BusConstant;
import com.zt.bus.line.inter.RefundDetailMapper;
import com.zt.bus.line.inter.RefundMapper;
import com.zt.bus.line.model.LinePlanRefund;
import com.zt.bus.line.model.Refund;
import com.zt.bus.line.model.RefundDetail;
import com.zt.servlet.FieldAlias;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.system.service.IFieldAliasService;
import com.zt.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class RefundService extends BaseService implements IFieldAliasService {

    @Autowired
    private RefundMapper refundMapper;

    @Autowired
    private RefundDetailMapper refundDetailMapper;
    
    @Autowired
    private LinePlanService linePlanService;

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    @FieldAlias(service = "refundService", field = "refundId", alias = "refundDetails")
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("");
        sqlBuilder.appendSql("select * from DZ_REFUND where C_REFUND_STATUS = ? ", BusConstant.RefundStatus.ENABLE);
        sqlBuilder.addWhereLike2("REFUND_NAME", reqBean.getInfo("refundName"));
        sqlBuilder.addWhere("C_REFUND_TYPE", reqBean.getInfo("refundType"));
        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 通过id查询
     * 
     * @param refundId
     * @return
     */
    @Cacheable(value = "_refundCache", key = "#refundId")
    public Refund getById(String refundId) {
        Refund refund = refundMapper.selectByPrimaryKey(refundId);
        if (refund != null) {
            refund.setDetails(refundDetailMapper.selectEnableByRefundId(refund.getId()));
        }
        return refund;
    }

    /**
     * 新增
     * 
     * @param refund
     */
    public void add(Refund refund, List<RefundDetail> refundDetails) {
        refund.setId(intIncrementId("DZ_REFUND", "REFUND_ID"));// 手动设置Id
        refund.setMakeTime(new Date());
        refund.setModifyTime(refund.getMakeTime());
        refund.setStatus(BusConstant.RefundStatus.ENABLE);
        refundMapper.insert(refund);

        if (refundDetails != null && refundDetails.size() > 0) {
            for (int i = 0; i < refundDetails.size(); i++) {
                RefundDetail refundDetail = refundDetails.get(i);
                refundDetail.setRefundId(refund.getId());
                refundDetail.setId(intIncrementId("DZ_REFUND_DETAIL", "REFUND_DETAIL_ID"));
                refundDetail.setStatus(BusConstant.RefundDetailStatus.ENABLE);
                refundDetailMapper.insert(refundDetail);
            }
        }

    }

    /**
     * 修改
     * 
     * @param refund
     */
    @CacheEvict(value = BusConstant.Cache.REFUND, allEntries = true)
    public void update(Refund refund, List<RefundDetail> refundDetails, JSONArray deleteRefundDetailList) {

        String refundId = refund.getId();
        if (StringUtil.isEmpty(refundId)) {
            throw new BusinessException("获取主键失败");
        }

        Date now = new Date();

        refund.setModifyTime(now);
        refundMapper.updateByPrimaryKeySelective(refund);

        if (refundDetails != null && refundDetails.size() > 0) {
            for (int i = 0; i < refundDetails.size(); i++) {
                RefundDetail refundDetail = refundDetails.get(i);
                if (StringUtils.isBlank(refundDetail.getId())) { // 等于空，新增
                    refundDetail.setRefundId(refund.getId());
                    refundDetail.setId(intIncrementId("DZ_REFUND_DETAIL", "REFUND_DETAIL_ID"));
                    refundDetail.setStatus(BusConstant.RefundDetailStatus.ENABLE);
                    refundDetailMapper.insert(refundDetail);
                } else { // 不等于空，修改
                    RefundDetail refundDetailBean = refundDetailMapper.selectByPrimaryKey(refundDetail.getId());
                    if (BusConstant.RefundType.TIME_DISCOUNT_RATE.equals(refund.getType())) { // 发车前时间折扣率
                        refundDetailBean.setRefundRate(refundDetail.getRefundRate());
                        refundDetailBean.setMinutes(refundDetail.getMinutes());
                    } else {
                        refundDetailBean.setFixedFee(refundDetail.getFixedFee());
                    }
                    refundDetailBean.setRefundRate(refundDetail.getRefundRate());
                    refundDetailBean.setStatus(refundDetail.getStatus());
                    refundDetailBean.setModifyTime(now);
                    refundDetailBean.setRemark(refundDetail.getRemark());
                    refundDetailMapper.updateByPrimaryKeySelective(refundDetailBean);
                }
            }
        }
//        删除确定删除的明细
        if(deleteRefundDetailList != null && deleteRefundDetailList.size() > 0) {
            for (int i = 0; i < deleteRefundDetailList.size(); i++) {
                JSONObject json = deleteRefundDetailList.getJSONObject(i);
                deleteDetail(json.getString("refundDetailId"));
            }

        }

    }

    /**
     * 删除
     * 
     * @param refundId
     */
    @CacheEvict(value = BusConstant.Cache.REFUND, allEntries = true)
    public void delete(String refundId, String userId) {
        if (StringUtils.isBlank(refundId)) {
            throw new BusinessException("缺少参数!");
        }

        Date now = new Date();
        Refund refund = refundMapper.selectByPrimaryKey(refundId);
        refund.setStatus(BusConstant.RefundStatus.DISABLE);
        refund.setModifyTime(now);
        refundMapper.updateByPrimaryKeySelective(refund);

        List<RefundDetail> refundDetails = refundDetailMapper.selectEnableByRefundId(refundId);
        for (int i = 0; i < refundDetails.size(); i++) {
            RefundDetail refundDetail = refundDetails.get(i);
            refundDetail.setStatus(BusConstant.RefundDetailStatus.DISABLE);
            refundDetail.setModifyTime(now);
            refundDetail.setOperator(userId);
            refundDetailMapper.updateByPrimaryKeySelective(refundDetail);
        }
    }

    /**
     * 删除详情
     * 
     * @param refundDetailId
     */
    @CacheEvict(value = BusConstant.Cache.REFUND, allEntries = true)
    public void deleteDetail(String refundDetailId) {
        if (StringUtils.isBlank(refundDetailId)) {
            throw new BusinessException("缺少参数");
        }
        RefundDetail detail = refundDetailMapper.selectByPrimaryKey(refundDetailId);
        detail.setStatus(BusConstant.RefundDetailStatus.DISABLE);
        detail.setModifyTime(new Date());
        refundDetailMapper.updateByPrimaryKeySelective(detail);
    }

    /**
     * 获取详情
     * 
     * @param fields
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> dealFieldAlias(List<Object> fields, String param) {
        Map<String, Object> map = new HashedMap();
        for (Object field : fields) {
            map.put((String) field, new JSONArray());
        }
        SqlBuilder sqlBuilder = new SqlBuilder("SELECT * FROM DZ_REFUND_DETAIL where C_REFUND_DETAIL_STATUS = ? ",
                BusConstant.RefundDetailStatus.ENABLE).addWhereIn("REFUND_ID", fields);
        JSONArray array = query(sqlBuilder);
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            String refundId = json.getString("refundId");
            ((JSONArray) map.get(refundId)).add(json);
        }
        return map;
    }
    
	/**
	 * 通过orderId获得退款方案
	 * 
	 * @param orderId
	 * @return
	 */
	public Refund getRefundByPlanId(String planId) {
		// 获得线路方案退款方案
		 LinePlanRefund linePlanRefund = linePlanService.getLinePlanRefund(planId);
		// 退款方案
		return getById(linePlanRefund.getRefundId());
	}
}
